//
// Created by xili on 2024/10/9 10:10.
// GO BIG OR GO HOME.
//
#include "leetcode.h"

class Solution {
public:
    ListNode* reverseEvenLengthGroups(ListNode* head) {
        int i = 0;
        ListNode* cur = head;
        ListNode* pre = nullptr;
        while (cur) {
            ++i;
            ListNode* it = cur;
            int len = 0;
            for (; len < i && it; ++len) {
                it = it->next;
            }

            if (len & 1) {
                for (int j = 1; j <= len; ++j) {
                    tie(pre, cur) = tuple{cur, cur->next};
                }
            }
            else {
                for (int j = 1; j < len; ++j) {
                    tie(pre->next, cur->next, cur->next->next) = tuple{cur->next, cur->next->next, pre->next};
                }
                tie(pre, cur) = tuple{cur, cur->next};
            }
        }
        return head;
    }
};
